package com.gaohc.framework.config.encrypt;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

public class SM4Util {
    private static String secretKey = "1234567890123456";
    private static String iv = "1234567890123456";

    public SM4Util() {
    }

    public static String encrypt(String plainTxt) {
        String cipherTxt = "";
        SymmetricCrypto sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, secretKey.getBytes(CharsetUtil.CHARSET_UTF_8), iv.getBytes(CharsetUtil.CHARSET_UTF_8));
        byte[] encrypHex = sm4.encrypt(plainTxt);
        cipherTxt = Base64.encode(encrypHex);
        return cipherTxt;
    }

    public static String decrypt(String cipherTxt) {
        String plainTxt = "";

        try {
            SymmetricCrypto sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, secretKey.getBytes(CharsetUtil.CHARSET_UTF_8), iv.getBytes(CharsetUtil.CHARSET_UTF_8));
            byte[] cipherHex = Base64.decode(cipherTxt.trim());
            plainTxt = sm4.decryptStr(cipherHex, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return plainTxt;
    }

}
